package com.yy.young.cms.service.impl;

import com.yy.young.base.exception.ParameterException;
import com.yy.young.cms.model.Column;
import com.yy.young.cms.model.Table;
import com.yy.young.cms.service.ICmsDBService;
import com.yy.young.cms.service.ICmsTableColService;
import com.yy.young.cms.service.ICmsTableService;
import com.yy.young.cms.util.CmsConstants;
import com.yy.young.dal.service.IDataAccessService;
import com.yy.young.dal.util.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 业务表服务实现
 * Created by rookie on 2017/8/11.
 */
@Service("cmsTableService")
public class CmsTableServiceImpl implements ICmsTableService {

    @Resource(name = "dataAccessService")
    IDataAccessService dataAccessService;//数据层服务

    @Resource(name = "cmsDBService")
    ICmsDBService cmsDBService;

    @Resource(name = "cmsTableColService")
    ICmsTableColService cmsTableColService;

    @Override
    public List<Table> getTableList(Table table) throws Exception {
        return dataAccessService.getList(CmsConstants.MAPPER.CMS_TABLE + ".getTable", table);
    }

    @Override
    public Table getTable(String tableId) throws Exception {
        return (Table)dataAccessService.getObject(CmsConstants.MAPPER.CMS_TABLE + ".getTableById", tableId);
    }

    @Override
    public List<Table> getTablePage(Table table, Page page) throws Exception {
        return dataAccessService.getList(CmsConstants.MAPPER.CMS_TABLE + ".getTable", table, page);
    }

    @Override
    public int updateTable(Table table) throws Exception {
        return dataAccessService.update(CmsConstants.MAPPER.CMS_TABLE + ".updateTable", table);
    }

    @Override
    public int deleteTable(String[] idsArr) throws Exception {
        //删除表的字段记录
        for (String tableId : idsArr){
            cmsTableColService.deleteAllColInfo(tableId);
        }
        //删除业务表记录
        int num = dataAccessService.delete(CmsConstants.MAPPER.CMS_TABLE + ".deleteTable", idsArr);
        //删除表
        for (String tableId : idsArr){
            cmsDBService.dropTable(tableId);
        }
        return num;
    }

    @Override
    public int insertTable(Table table) throws Exception {
        if (getTable(table.getId()) != null){
            throw new ParameterException("已存在表"+table.getId()+"的信息!");
        }
        table.setCreateTime(new Date());//创建时间
        table.setColumnList(CmsConstants.DEFAULT_CMS_COLUMNS);
        //插入表记录
        int num = dataAccessService.insert(CmsConstants.MAPPER.CMS_TABLE + ".insertTable", table);
        cmsDBService.createTable(table);//建表
        return num;
    }

}
